package com.cutJar.core.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;

import com.conf.log.LOG;
import com.conf.log.impl.LogImpl;
import com.cutJar.Exception.CutNullException;
import com.cutJar.Exception.ResourceNullException;
import com.cutJar.core.AbstractCutJARImpl;
import com.cutJar.core.AbstractMachining;
import com.cutJar.core.CutJAR;
import com.cutJar.util.CharStream;
import com.cutJar.util.Resource;

/**
 * <b>自定义剪切-也可以剪切rt和charsets</b>
 * <p>
 * 描述:<br>
 * 
 * @author 威 
 * <br>2018年3月31日 下午5:25:14 
 * @see com.cutJar.core.AbstractCutJARImpl
 * @since 1.0
 */
public class CutJARImpl_Def extends AbstractCutJARImpl {
	private CutJAR cutJAR;
	private String dectoryName;
	private String jrePath;
	
	/**
	 * 设置初始参数
	 * <p>	 
	 * @param dectoryName	文件名称(charsets、rt)
	 * @param jrePath		jre路径/lib
	 * @return
	 * CutJARImpl_Def
	 * @see
	 * @since 1.0
	 */
	public CutJARImpl_Def param(String dectoryName, String jrePath){
		this.dectoryName = dectoryName;
		this.jrePath = jrePath;
		return this;
	}
	
	@Override
	public CutJARImpl_Def cutPre() throws ResourceNullException {
		File tempTextFile = Resource.getResource("pre", "temp.txt");
		AbstractMachining machining = new DefMachiningImpl();
		BufferedReader br = null;
		BufferedWriter bw = null;
		if(tempTextFile.exists()) {
			try {
				br = CharStream.getRead(tempTextFile);
				bw = CharStream.getWrite(Resource.getResource("pre", "class.txt"));
				String line;
				while((line = br.readLine()) != null){
					bw.write(line);
					bw.newLine();
				}
			} catch (IOException e) {
				e.printStackTrace();
				LogImpl.getInstance().log(LOG.ERROR, e.getMessage());
			}finally{
				try {
					CharStream.free(br);
					CharStream.free(bw);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		machining.configure(dectoryName, Resource.getResurceToString("pre", "class.txt"));
		machining.cutPreStart();
		machining.logResultInfo();
		return this;
	}

	@Override
	public void cutStart() {
		cutJAR = new CutJAR();
		try {
			//剪切自定义包
			cutJAR.configure(jrePath, Resource.getResurceToString("pre", dectoryName)).cutStart();
		} catch (CutNullException | ResourceNullException e) {
			LogImpl.getInstance().log(LOG.ERROR, e.getMessage());
		}
	}
	
}
